/**
 * 继承Acitivity
 * 所有显示类的父类
 * */

package com.rytong.tools.ui;

import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.UUID;
import java.util.Vector;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import com.rytong.tools.R;
import com.rytong.tools.offstore.OffStoreDownload;
import com.rytong.tools.androidpn.client.ServiceManager;
import com.rytong.tools.datastorage.PreferenceDB;
import com.rytong.tools.datastorage.SqlDb;
import com.rytong.tools.httpconnect.HttpManager;
import com.rytong.tools.parserwidgets.ParseWidgets;
import com.rytong.tools.ui.LPTextField;
import com.rytong.tools.ui.LPTextField.MyLPTextField;
import com.rytong.tools.utils.AppAntiService;
import com.rytong.tools.utils.HomeKeyBroadCastReceiver;
import com.rytong.tools.utils.Utils;

public abstract class BaseView extends Activity {
    // 是否已计算状态栏标志位
    private boolean haveTop_;
    // 离线存储对象
    public static OffStoreDownload OFFSTORED;
    // 新加密码临时变量，保证一个form只用一次key和iv
    byte[] keyTemp_;
    byte[] ivTemp_;
    final public static String CERTIFICATE = "xx_ca_test.png";

    // 处理webview里camera的handler
    Handler cameraHandler_;
    //增加联系人
	private Vector<String> phonesVector = null;
	private int phoneIndex = 0;
	private MyLPTextField scanTextField = null;
	private String[] arrTemp;
	private EditText phoneTextField = null;
	Class<?> clsContacts = null;
	Class<?> clsPhone = null;
	static final int PICK_CONTACT = 201;
	static final int PICK_BROWSER = 402;
    // 单元测试设置标记
    static public boolean UNITTESTFLAG;
    
    // 图片缓存。
    public Map<String, SoftReference<Bitmap>> bmCache_ = null;
    
    // 文本框最大长度
    public int maxSize = 0;
    
    //存activity的list，方便管理activity
    public static final List<Activity> activityList = new LinkedList<Activity>();

    /**
     * 监听home键的广播类
     */
	public static HomeKeyBroadCastReceiver keyReceiver;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        getStatusBarHeight();
        Utils.initCustomerSecretKey(this);
        
		initAppAnti();
    }

    private void getStatusBarHeight() {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0;
        try {
            c = Class.forName(Utils.getConfigStringFormAsset(this, "cominternal"));
            obj = c.newInstance();
            field = c.getField(Utils.getConfigStringFormAsset(this, "statusbarheight"));
            x = Integer.parseInt(field.get(obj).toString());
            int statusBarHeight = getResources().getDimensionPixelSize(x);

            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            Component.SCREENHEIGHT = dm.heightPixels - statusBarHeight;
        } catch (Exception e) {
            Utils.printException(e);
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (!haveTop_) {
            Rect frame = new Rect();
            getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int statusBarHeight = frame.top;
            Component.SCREENHEIGHT = dm.heightPixels - statusBarHeight;
            haveTop_ = true;
        }
        super.onWindowFocusChanged(hasFocus);
    }

    /**
     * 根据网络连接模式，激活网络
     * 
     * @param bv
     *            界面参数
     */
    public void openNetworkByModel(Activity bv) {
        try {
            final String CDMA777 = "#777:CDMA";
            final String TD_HSDPA = "TD_HSDPA";
            final String CMWAP = "wap";
            final String CMNET = "cmnet";
            Context context = bv.getApplicationContext();
            ConnectivityManager connectivity = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo ni = connectivity.getActiveNetworkInfo();

            if ((null != ni) && ni.isAvailable()) {
                String nameType = ni.getTypeName();
                String extraInfo;
                if (!nameType.equalsIgnoreCase("wifi")) {
                    NetworkInfo[] info = connectivity.getAllNetworkInfo();
                    if (info != null) {
                        for (int i = 0; i < info.length; i++) {
                            extraInfo = info[i].getExtraInfo();
                            if ((extraInfo.indexOf("ctnet") != -1) || extraInfo.indexOf("ctwap") != -1
                                    || extraInfo.equalsIgnoreCase(CDMA777)) {
                                connectivity.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "*");
                                return;
                                // 表示是电信的手机,处理方法稍有不同
                                // setCmwapAPN();
                                // return;
                            }
                            if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                                String subType = info[i].getSubtypeName();
                                // 此处判断连接类型,由于没有比较直观的反应wap和net的相关差异�?
                                // 所以此处比较粗糙以后应该修正
                                if (subType.equalsIgnoreCase(TD_HSDPA) || extraInfo.contains(CMWAP)) {
                                    connectivity.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, CMWAP);
                                    HttpManager.CONNECTYPE = 1;
                                    return;
                                } else {
                                    connectivity.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, CMNET);
                                    return;
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            Utils.printException(e);
        }

    }

    /**
     * 所有的初始化操作在此完成
     */
    public void initObject(Activity activity) {
        // TODO Auto-generated method stub
        Component.ACTIONV = new Stack();
        // 单元测试标记置否，表示为非单元测试环境
        UNITTESTFLAG = false;
        // 根据Config中的isprintMessage标志设置是否开启打印开关
        Utils.setPrint(activity);
        Utils.getAppName(activity);
        Utils.getPlatform(activity);
        Utils.readTextClolr(activity);
        // 选择网络APN
        openNetworkByModel(activity);
        catchException();
        // 隐藏系统标题栏
        //hideSystemBar(activity);
        // 计算手机界面的宽高
        Utils.calculateScreenSize(activity);
        // 读取本地的控件列表并进行相应的存储
        readWidget();
        OffStoreDownload.setRootPath();
        // 初始化弹出框集合
        Component.DIALOGHASH = new HashMap();
        // 初始化离线存储功能模块
        OFFSTORED = new OffStoreDownload(activity);
        String usePush = Utils.getConfigStringFormAsset(this, "usePush");
        if (usePush != null && usePush.trim().equalsIgnoreCase("true")) {
            // Start the service
            ServiceManager serviceManager = new ServiceManager(activity);
            serviceManager.setNotificationIcon(Utils.getResourcesId(activity, "icon", "drawable"));
            serviceManager.startService();
            // ServiceManager.viewNotificationSettings(this);
        }
    }

    private void catchException() {
        // 捕获运行时异常,将捕获到的异常发送到指定服务器，同时
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread thread, Throwable ex) {
            	if(null != ex && null != ex.getLocalizedMessage()){
            		Utils.printOutToConsole(ex.getLocalizedMessage());
            		Utils.printOutToConsole(ex.getMessage());            		
            		//Log.e("uncaughtException", ex.getLocalizedMessage());
            	}
            	exitSystem();
            }
        });
    }

	/**
	 * 退出程序
	 */
	public void exitSystem() {
		finishAppAnti();
		/**
		 * 当退出时，要结束List中的所有activity add by chengli
		 * */
		for(Activity activity:activityList){
			if(null != activity){				
				activity.finish();
			}
		}
		// 停止程序开启的服务，保证程序退出后不会常驻内存
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(10);
	}
	
    /**
     * 得到 一个随机的uuid
     * @return
     */
    public String newRandomUUID() {
        String uuidRaw = UUID.randomUUID().toString();
        return uuidRaw.replaceAll("-", "");
    }
    
    /**
     * 退出程序时终止所有的防劫持服务
     */
    public void finishAppAnti(){
		if(null != keyReceiver){
			unregisterReceiver(keyReceiver);
			keyReceiver = null;
		}
		stopAppAntiService();
    }

    /**
     * 启动防劫持服务
     */
    public void startAppAntiService(){
        Thread serviceThread = new Thread(new Runnable() {
            @Override
            public void run() {
            	Intent intent = new Intent(BaseView.this, AppAntiService.class);
            	startService(intent);
            }
        });
        serviceThread.start();
    }

	/**
	 * 停止防劫持服务
	 */
	public void stopAppAntiService() {
		Intent intent = new Intent(this, AppAntiService.class);
		stopService(intent);
	}
    /**
	 * 启动防劫持服务
	 */
	public void initAppAnti(){
        //启动反劫持服务
		if(null == keyReceiver){
			startAppAntiService();
			keyReceiver = new HomeKeyBroadCastReceiver();			
		}
        registerReceiver(keyReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
	}

	@Override
	public void onResume() {
		AppAntiService.isPressHomeKey = false;
		if(null != keyReceiver){
			registerReceiver(keyReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));		
		}
		super.onResume();
	}
	
    @Override
    public void onDestroy() {
    	try{
    		/**
    		 * 如果应用程序退到后台，用户主动杀掉进程把服务结束掉
    		 */
    		if(AppAntiService.isPressHomeKey){
    			stopAppAntiService();
    		}
    		
    		if(null != keyReceiver){
    			unregisterReceiver(keyReceiver);
    		}
            // 清空图片缓存。
            if(bmCache_ != null){
            	if(bmCache_.keySet() != null){
            		Iterator<String> iterator = bmCache_.keySet().iterator();
            		while (iterator.hasNext()) {
    					String key = (String) iterator.next();
    					if(bmCache_.get(key) != null && bmCache_.get(key).get() != null
    							&& !bmCache_.get(key).get().isRecycled()){
    						bmCache_.get(key).get().recycle();
    						bmCache_.put(key, null);
    					}
    				}
            	}
            	bmCache_.clear();
            	bmCache_ = null;
            }
            IsLKName = false ; //清空是否需要添加联系人姓名的判断
    	}catch(Exception e){
    		e.printStackTrace();
    	}
        super.onDestroy();
    }

    /**
     * 隐藏界面状态栏
     * 
     * @param activity
     */
    protected void hideSystemBar(Activity activity) {
        // No Statusbar隐藏界面最上方状态栏
        // Window win = activity.getWindow();
        // win.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        // WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // 隐藏android系统定义的标题栏
        activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    /**
     * 
     */
    protected void initScreenManager() {
        hideSystemBar(this);
    }

    /**
     * 当横竖屏切换时调用此方法交换屏幕宽高
     * 
     * @param roientation
     *            int 横竖屏标�?
     * */
    public void changeScreenWidthHeight(int roientation) {
        int w = Component.SCREENWIDTH;
        int h = Component.SCREENHEIGHT;
        if (roientation == Configuration.ORIENTATION_LANDSCAPE && h > w) {
            // 横屏。交�?screenHeight_ �?screenWidht_ 的值�?
            h = h + w;
            w = h - w;
            h = h - w;
        } else if (roientation == Configuration.ORIENTATION_PORTRAIT && h < w) {
            // 竖屏。再交换 screenHeight_ �?screenWidht_ 的值，回复原值�?
            h = h + w;
            w = h - w;
            h = h - w;
        }
    }

    /**
     * @param link
     * @param bv
     */
    public void dealWithLink(String link, BaseView bv) {
        // TODO Auto-generated method stub
    }

    /*
     * ************************************************************************
     * local resources. ************************************************************************
     */
    /**
     * @param id
     *            String 资源id
     * @param version
     *            String 最新资源版本号
     * @return byte[]
     * */
    public byte[] get_local_content(String id, String version) {
        if (id == null || version == null) {
            Utils.printOutToConsole("In get_local_content(), id or version is null.");
            return null;
        }

        SqlDb mySqlDb = new SqlDb(this, "donghang_emp_db", null, 1);
        Cursor myCursor = mySqlDb.select();
        int rowCount = myCursor.getCount();// 存储数据库�?�录行数
        int row = 0;
        // 如果数据库中还没有数据则�?1
        if (rowCount > 0 && (row = getRowById(id, myCursor)) >= 0) {
            myCursor.moveToPosition(row);
            String resId = myCursor.getString(0);
            if (id.equals(resId)) {
                // 取得资源版本�?
                String oldVersion = myCursor.getString(1);
                // 如果版本号相同，则返回取得数?��
                if (version.equals(oldVersion)) {
                    byte[] b = myCursor.getBlob(2);
                    // 这里??��?�新资源被最后被访问的日�?
                    mySqlDb.update(id, version, b);
                    myCursor.close();
                    myCursor = null;
                    mySqlDb.close();
                    mySqlDb = null;
                    return b;
                }
            }
        }
        myCursor.close();
        myCursor = null;
        mySqlDb.close();
        mySqlDb = null;
        return null;
    }

    /**
     * @param id
     *            String 资�??id
     * @param version
     *            String 最新资源版本号
     * @param obj
     *            Object 要存储的资源
     * @param sqlRow
     *            int 行号�?1:存储新数据；sqlRow >= 0:更新第sqlRow行的数据
     * @return void
     * */
    public void save_local_content(String id, String version, byte[] value, PreferenceDB sqlSizeDB_) {
        if (id == null || version == null || value == null) {
            Utils.printOutToConsole("In save_local_content(), id or version or byte is null.");
            return;// 所??�值不能为�?
        }

        String resSizeId = "resSize";
        int sqlSize = 0;
        int row = 0;
        // 获得sql数据库大�?
        String str = sqlSizeDB_.get(resSizeId);
        if (str != null) {
            sqlSize = Integer.parseInt(str);
        }
        SqlDb mySqlDb = new SqlDb(this, "donghang_emp_db", null, 1);
        Cursor myCursor = mySqlDb.select();
        row = getRowById(id, myCursor);
        if (row != -1) {
            myCursor.moveToPosition(row);
            // 更新数�??时减去原来数据�??�?
            sqlSize -= value.length;
            mySqlDb.update(id, version, value);
        } else {
            mySqlDb.insert(id, version, value);
        }
        myCursor.close();
        myCursor = null;
        mySqlDb.close();
        mySqlDb = null;
        // 加上更新或添加的数据大小
        sqlSize += value.length;
        sqlSizeDB_.save(resSizeId, Integer.toString(sqlSize));
    }

    /**
     * 已缓存的数据清理
     * */
    public void sqlDataManager(PreferenceDB sqlSizeDB_) {
        String resSizeId = "resSize";
        final int MAXSIZE = 10000000;
        int sqlSize = 0;// 数据库大�?
        int sqlCount = 0;// 数据库记录条�?
        int row = 0;// 记录最久没有被访问的数据所在行�?
        long currentTimeMillis = 0;// 存储当前系统时间
        // 获得sql数据库大�?
        String str = sqlSizeDB_.get(resSizeId);
        if (str != null) {
            try {
                sqlSize = Integer.parseInt(str);
            } catch (Exception e) {
                Utils.printException(e);
            }
        }

        // 如果数据库小�?0M，则不执行清理操�?
        if (sqlSize < MAXSIZE)
            return;
        Cursor myCursor = null;
        SqlDb mySqlDb = null;
        do {
            // 获得当前系统时间，和数据库数据的存储时间比较，最长时间没有被访问的将被删�?
            currentTimeMillis = System.currentTimeMillis();
            mySqlDb = new SqlDb(this, "donghang_emp_db", null, 1);
            myCursor = mySqlDb.select();
            sqlCount = myCursor.getCount();
            for (int i = 0; i < sqlCount; i++) {
                myCursor.moveToPosition(i);
                long saveTimeMillis = myCursor.getLong(3);
                if (saveTimeMillis < currentTimeMillis) {
                    currentTimeMillis = saveTimeMillis;
                    row = i;
                }
            }
            myCursor.moveToPosition(row);
            sqlSize -= myCursor.getBlob(2).length;
            mySqlDb.delete(myCursor.getString(0));
        } while (sqlSize > MAXSIZE);
        myCursor.close();
        myCursor = null;
        mySqlDb.close();
        mySqlDb = null;
    }

    /**
     * 通过资源id获取资源所在行�?
     * 
     * @param id
     *            String 资源id
     * @return int 返回行索引，-1表示为找�?
     * */
    private int getRowById(String id, Cursor myCursor) {
        for (myCursor.moveToFirst(); !myCursor.isAfterLast(); myCursor.moveToNext()) {
            if (myCursor.getString(0).equals(id)) {
                // 资源ID与版本号相同，即找到数据，返回当前游标�?
                int row = myCursor.getPosition();
                myCursor = null;
                return row;
            }
        }
        return -1;
    }

    /**
     * 从widget.xml文件中读取整个软件应该会用到的控件集合
     */
    private void readWidget() {
        // TODO Auto-generated method stub
        try {
            String widget = Utils.getStringFormAsset(this, "widget.xml");
            ParseWidgets pw = new ParseWidgets();
            android.util.Xml.parse(widget, pw);
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
    }

    //增加联系人zd(添加号码)
	public void setPhoneLPTextField(EditText textField) {
		phoneTextField  = textField;
	}
	//添加联系人姓名
	EditText lknameTextField ;
	boolean IsLKName = false ;
	public void setlknameLPText(EditText lknTextField){
		lknameTextField = lknTextField ;
		IsLKName = true ;
	}
	//调出系统联系人界面
	public void getPeopleConnects(BaseView bv) {
		if (phonesVector != null) {
			phonesVector.clear();
		} else {
			phonesVector = new Vector<String>();
		}
		Uri uri = null;
		
		try {
				clsContacts = getDeclaredSubClass(
						"android.provider.ContactsContract", "Contacts"); //调用底层Contacts接口
				if (clsContacts != null) {
					Field field;
					try {
						field = clsContacts.getDeclaredField("CONTENT_URI");
						String varName = field.getName();
						Utils.printOutToConsole(varName);
						uri = (Uri) field.get(varName); //取值
					} catch (SecurityException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (NoSuchFieldException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			
		} catch (Exception ex) {
			
		}
		if (null != uri) {
			Intent intent = new Intent(Intent.ACTION_PICK, uri);
			startActivityForResult(intent, PICK_CONTACT);
		}
	}
	
	//找出android底层Contacts的接口
	private Class<?> getDeclaredSubClass(String superName, String subName) {
		Class<?> clsSuper;
		Class<?> clsContacts = null;
		try {
			clsSuper = Class.forName(superName);//返回与带有给定字符串名superName的类或接口相关联的 Class 对象

			Class<?>[] subClasses = clsSuper.getDeclaredClasses();//返回该类的所有成员或接口的数组
			for (Class<?> cls : subClasses) {
				if (cls.getSimpleName().equals(subName)) {
					clsContacts = cls;
					break;
				}
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return clsContacts;
	}

	private void alerError(String message) {
		new AlertDialog.Builder(BaseView.this).setTitle("提示").setMessage(
				message).setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {

					}

				}).show();
	}
	//联系人所有的号码
	String phonename ;
	private void getSelectedContactor(Uri uri) {
		Cursor cursor = null; //Cursor提供一个查询DB的接口
		Cursor phones = null;
		String phoneNumber = null;

		if (uri != null) {
			ContentResolver cr = getContentResolver();
			cursor = cr.query(uri, null, null, null, null);

			if (cursor != null && cursor.moveToFirst()) {
				try {
					String fieldID = (String) getFieldValue(clsContacts, "_ID");
					String fieldname = (String)getFieldValue(clsContacts, "DISPLAY_NAME");
					Utils.printOutToConsole("fieldname---------------------------->"+fieldname);
					String id = cursor.getString(cursor
							.getColumnIndexOrThrow(fieldID));
					phonename = cursor.getString(cursor.getColumnIndexOrThrow(fieldname));
					phonename = phonename.replaceAll(" ", "");
					Utils.printOutToConsole("phonename---------------------------->"+phonename);
					Class<?> clsCDK = getDeclaredSubClass(
							"android.provider.ContactsContract",
							"CommonDataKinds");
					clsPhone = getDeclaredSubClass(clsCDK.getName(), "Phone");
					Uri fieldURI = (Uri) getFieldValue(clsPhone, "CONTENT_URI");
					String fieldC_ID = (String) getFieldValue(clsPhone,
							"CONTACT_ID");
					String fieldP_NM = (String) getFieldValue(clsPhone,
							"NUMBER");

					phones = cr.query(fieldURI, null, fieldC_ID + "=" + id,
							null, null);

					if (phonesVector != null) {
						phonesVector.clear();
					} else {
						phonesVector = new Vector<String>();
					}

					while (phones.moveToNext()) {
						phoneNumber = phones.getString(phones
								.getColumnIndexOrThrow(fieldP_NM));
						phoneNumber = phoneNumber.replaceAll("\\D", "");
						if (phoneNumber.startsWith("86")) {
							phoneNumber = phoneNumber.substring(2);
						}
						phonesVector.add(phoneNumber);
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (phones != null) {
						phones.close();
						phones = null;
					}

					if (cursor != null) {
						cursor.close();
						cursor = null;
					}
				}
			}
		}
	}

	private Object getFieldValue(Class<?> cls, String fieldName) {
		Object obj = null;
		if (cls != null) {
			try {
				Field field = cls.getField(fieldName);
				if (!field.isAccessible()) {
					field.setAccessible(true);
				}
				obj = field.get(fieldName);
				Utils.printOutToConsole("field value: " + field);

			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return obj;
	}
	//选中联系人后 弹出选择号码单选框
	protected void showPhoneDialog(int index) {
		try {
			if ((phonesVector == null) || (phonesVector != null && phonesVector.size() == 0)) {
				if(null != phoneTextField){
					phoneTextField.setText("");
				}
				alerError("该联系人没有联系信息");
				return;
			} else if((phonesVector != null)&&(phonesVector.size() == 1)){
				if (phoneTextField != null ) {
					phoneTextField.setText(phonesVector.get(0));
					bundleDataText(phoneTextField,phonesVector.get(0));
				}
				if (phonesVector != null) {
					phonesVector.clear();
				}
				//添加联系人姓名
				if(IsLKName==true){
					lknameTextField.setText(phonename);
					bundleDataText(lknameTextField,phonename);
				}
				return;
			}else {
				String[] contents = new String[phonesVector.size()];
				for (int i = 0; i < phonesVector.size(); i++) {
					contents[i] = phonesVector.get(i);
				}
				phoneIndex = 0;
				new AlertDialog.Builder(this).setTitle((this.getResources().getString(R.string.selectPhones)))
					.setSingleChoiceItems(contents, 0,
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog,
								int whichButton) {
							changePhoneIndex(whichButton);
						}
					})
					.setPositiveButton((this.getResources().getString(R.string.sure)),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// 此处 用要赋值的组件的索引来完成赋值操作
							if (phoneTextField != null ) {
								phoneTextField.setText(phonesVector.get(phoneIndex));
								bundleDataText(phoneTextField,phonesVector.get(phoneIndex));
							}
							if (phonesVector != null) {
								phonesVector.clear();
							}
							//添加联系人姓名
							if(IsLKName==true){
								lknameTextField.setText(phonename);
								bundleDataText(lknameTextField,phonename);
							}
						}
					}
				).show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void changePhoneIndex(int which) {
		phoneIndex = which;
	}
	
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Utils.CAMERA_REQUEST_CODE == requestCode) { // 系统相机返回处理
            Message message = new Message();
            // 执行js回调函数
            if (resultCode == Activity.RESULT_OK) {
                message.what = 1;
                cameraHandler_.sendMessage(message);

            } else {
                message.what = 2;
                cameraHandler_.sendMessage(message);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
        //增加联系人
    	if (resultCode == Activity.RESULT_OK) {
			if (requestCode == BaseView.PICK_CONTACT) {
				if (data == null) {
					alerError("无返回数据");
					return;
				}
				ContentResolver contentResolver = getContentResolver();
				if (contentResolver == null) {
					alerError("ContentResolver Error");
					return;
				}
				if (contentResolver != null) {
					Uri uri = data.getData();
					if (uri == null) {
						alerError("该机型不支持读取联系人信息");
						return;
					}
					if (uri != null) {
							getSelectedContactor(uri);
							showPhoneDialog(0);
						
					}
				}
			}
		}
    }

    public void bundleDataText(EditText et,String value){
    	if(et instanceof LPTextField.MyLPTextField){
			Component lptext=((LPTextField.MyLPTextField)et).composited();
			lptext.setPropertyByName("value", value);
		}
    }
}
